% These scripts are started to read and process the US array MT data
% from the IRIS website. There are some issues with the Canadian data 1)
% time shift 2) proper scaling ?

% Add the java path to the IRIS jar file

javaaddpath('/Users/manojnair/java/matlab_iris/IRIS-WS-2.0.2.jar');
%javaaddpath('/home/mnair/iris_matlab_java/IRIS-WS-1.5.2.jar');
% Fetch data form IRIS
%   args: Net, Sta, Loc, Cha, Starttime, Endtime [,quality][,includePZ][,verbosity]
	
rc010=irisFetch.Traces('EM','RC010','*','LFZ','2008-09-14 19:12:15', '2008-09-30 19:12:15');
rc020=irisFetch.Traces('EM','RC020','*','LFZ','2008-09-18 19:12:15', '2008-09-30 19:12:15');
rc010_time = linspace(rc010(1).startTime, rc010(1).endTime, rc010(1).sampleCount);
rc020_time = linspace(rc020(1).startTime, rc020(1).endTime, rc020(1).sampleCount);
rc030=irisFetch.Traces('EM','RC030','*','LFZ','2008-09-14 19:12:15', '2008-09-30 19:12:15');
rc030_time = linspace(rc030(1).startTime, rc030(1).endTime, rc030(1).sampleCount);
rc040=irisFetch.Traces('EM','RC040','*','LFZ','2008-09-14 19:12:15', '2008-09-30 19:12:15');
rc040_time = linspace(rc040(1).startTime, rc040(1).endTime, rc040(1).sampleCount);
MNC35 = irisFetch.Traces('EM','MNC35','*','LQE','2012-07-10 00:00:00', '2012-07-20 00:00:00');

plot(rc010_time, (rc010(1).data/rc010(1).sensitivity)*1e9 ,'r');
hold
plot(rc020_time, (rc020(1).data/rc020(1).sensitivity)*1e9 ,'b');
plot(rc030_time, (rc030(1).data/rc030(1).sensitivity)*1e9 ,'g');
plot(rc040_time, (rc040(1).data/rc040(1).sensitivity)*1e9 ,'k');
datetick;
legend('rc010','rc020','rc030','rc040');
ylabel('E (nT)');
title('Canadian Array data 2008-09-14 to 2008-09-30');


% Outstanding issues
% Apparent Time shift between stations
% Proper calibration of the files

mtb19=irisFetch.Traces('EM','MTB19','*','*','2009-09-01 19:12:15', '2009-09-15 19:12:15');
mtb19_time = linspace(mtb19(1).startTime, mtb19(1).endTime, mtb19(1).sampleCount);
plot(mtb19_time, ((mtb19(1).data - nanmean(mtb19(1).data))/mtb19(1).sensitivity)*1e9 ,'k');

mtb20=irisFetch.Traces('EM','MTB20','*','*','2009-09-01 19:12:15', '2009-09-15 19:12:15');
mtb20_time = linspace(mtb20(1).startTime, mtb20(1).endTime, mtb20(1).sampleCount);
plot(mtb20_time, ((mtb20(1).data-nanmean(mtb20(1).data))/mtb20(1).sensitivity)*1e9 ,'r');

mytrace = rc010;

data = [];        % each column will contain a different trace's data
sampletimes = []; % sampletime(x,y) contains the corresponding sample time for data(x,y)

for n=1:numel(mytrace)
  thistrace = mytrace(n);
  nSamples = thistrace.sampleCount;

  % scale, and then copy into the nth column of array data after scaling
  data(1:thistrace.sampleCount,n)=thistrace.data ./ thistrace.sensitivity; 

  % fill sampletimes with evenly-spaced times spanning from startTime to endTime
  sampletimes(1:nSamples,n)= linspace(thistrace.startTime,thistrace.endTime,nSamples);
end

sampletimes(sampletimes==0)=nan; % keep padded values from plotting

plot(sampletimes,data * 1e9,'b');


